package com.jerry.project;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

public class TagServlet extends HttpServlet {
	@Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
		JSONObject jsonobj=null;
		String tag=null;
		
		try {
			jsonobj=new JSONObject(reqToJSONString.reqToJSONString(req));
			if(jsonobj.has("tag")){
				tag=jsonobj.getString("tag");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	    Key tagKey = KeyFactory.createKey("TagKind", "tag");
	    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    if(tag!=null){
	    	Entity tags = new Entity("Tag", tagKey);
	    	tags.setProperty("tag", tag);
	    	datastore.put(tags);
        	resp.getWriter().write(1);
        }
	    else{
	    	resp.getWriter().write(0);
	    }
	}
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
		Key tagKey = KeyFactory.createKey("TagKind", "tag");
	    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    Query query = new Query("Tag", tagKey);
	    List<Entity> tags = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(100));
	    resp.getWriter().write("123");
	}
}
